package com.ctfo.ulcp.exp.db

import org.jetbrains.exposed.sql.*

data class TableDescriptor(
    var id: Int?,
    var resourceId: Int?,
    val name: String,
    val summary: String,
    val commentSrc: CommentSrc
)

object TableDescriptors : Table("t_table_descriptor") {

    private val id = integer("ID").autoIncrement()
    private val resourceId = integer("RESOURCE_ID")
    private val name = varchar("NAME", length = 255)
    private val summary = text("SUMMARY")

    private val commentSrc = varchar("COMMENT_SRC", length = 255)

    override val primaryKey = PrimaryKey(id)

    fun findBy(resourceId: Int, name: String): TableDescriptor? {
        return TableDescriptors.selectAll()
            .where { (TableDescriptors.resourceId eq resourceId).and(TableDescriptors.name eq name) }
            .map {
                TableDescriptor(
                    it[id],
                    resourceId,
                    it[TableDescriptors.name],
                    it[summary],
                    CommentSrc.valueOf(it[commentSrc])
                )
            }.firstOrNull()
    }

    fun save(t: TableDescriptor) {
        if (t.id == null) {
            t.id = TableDescriptors.insert {
                it[resourceId] = t.resourceId!!
                it[name] = t.name
                it[summary] = t.summary
                it[commentSrc] = t.commentSrc.name
            }[id]
        } else {
            TableDescriptors.update({ id eq t.id!! }) {
                it[summary] = t.summary
                it[commentSrc] = t.commentSrc.name
            }
        }
    }


}